<template>
  <view class="order-page u-p-20">
    <view class="u-font-lg u-m-b-20" style="margin-left: 120px;margin-top: 5px;">🧾 您选购的商品</view>
    <u-divider text="分割线" dot />

   <view v-for="(item, index) in cartList" :key="index" class="item-container u-m-b-20" style="border-bottom: 1px solid #e5e5e5; padding: 10px 0;">
     <view style="display: flex; align-items: center;">
       <!-- 左边图片 -->
       <image 
         :src="item.img ? item.img : '/static/default.png'" 
         style="width: 80px; height: 80px; border-radius: 8px;" 
       />
   
       <!-- 右边文字区域 -->
       <view style="flex: 1; padding-left: 20px; display: flex; flex-direction: column; justify-content: space-between; height: 80px;">
         <view style="font-size: 18px; font-weight: bold;">{{ item.name }}</view>
         <view style="font-size: 14px; color: #666;">{{ item.specText }}</view>
         <view style="display: flex; justify-content: space-between; align-items: center;">
           <text style="font-size: 14px;">￥{{ item.price.toFixed(2) }}/份</text>
           <view style="display: flex; align-items: center;">
             <u-icon name="minus-circle" size="22" @click="decreaseQuantity(index)" />
             <text style="margin: 0 10px;">{{ item.quantity }}</text>
             <u-icon name="plus-circle" size="22" @click="increaseQuantity(index)" />
           </view>
         </view>
       </view>
     </view>
   </view>


    <!-- 总计 -->
    <u-divider>总计</u-divider>
    <!-- 页面底部操作栏 -->
    <view style="position: fixed; bottom: 0; left: 0; right: 0; height: 100rpx; background: #fff; display: flex; justify-content: space-between; align-items: center; padding: 0 30rpx; box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1); z-index: 999;">
      <text class="u-type-primary" style="font-size: 18px;">合计金额：￥{{ totalMoney }}</text>
      <view>
        <u-button type="success" size="mini" style="width: 50rpx; height: 70rpx; font-size: 26rpx;" @click="confirmGoods">
          提交订单
        </u-button>
      </view>
    </view>
	<!-- 收货信息弹窗 -->
	    <view v-if="showAddressModal" class="modal-overlay">
	      <view class="modal-container">
	        <view class="modal-header">请填写收获信息</view>
	
	        <view class="modal-body">
	          <input v-model="receiverAddress" placeholder="收获地址" class="input" />
	          <input v-model="receiverPhone" placeholder="手机号" type="number" class="input" />
	          <input v-model="receiverName" placeholder="收件人姓名" class="input" />
	          <input v-model="distributionId" placeholder="推荐人编号" class="input" />
	        </view>
	
	        <view class="modal-footer">
	          <u-button plain @click="showAddressModal = false">返回</u-button>
	          <u-button type="primary" @click="confirmSubmit">确定</u-button>
	        </view>
	      </view>
	    </view>
  </view>
</template>

<script>
import { submitOrders, payOrder } from '@/api/orderArtGoods.js'

export default {
  data() {
    return {
      cartList: [],
	  stored:[],//cartList-----购物车过来的数据
	  stored2:[],//cartList2----详情页立即购买的数据
	  showAddressModal: false,//收获地址信息弹窗
	  receiverAddress: '',//收获地址
	  receiverPhone: '',//收获手机号
	  receiverName: '',//收获姓名
	  distributionId: '',//推荐人
    }
  },
  computed: {
    totalMoney() {
      return this.cartList.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)
    }
  },
  
  mounted() {
    this.getCarList()
  },
  onUnload() {
    this.cartList = []
    this.stored = []
    this.stored2 = []
  },
  methods: {
    getCarList() {
		this.stored = uni.getStorageSync('cartList') || []
	    this.stored2 = uni.getStorageSync('cartList2') || []
	  if (this.stored2 && this.stored2.length > 0) {
	      this.cartList = this.stored2
		  // uni.removeStorageSync('cartList2')  // 清除缓存
	    } else if (this.stored) {
	      this.cartList = this.stored
	    }
        console.log('接收到购物车数据：', this.cartList)
    },
    decreaseQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity > 1) {
        item.quantity--
		uni.setStorageSync('cartList2', this.cartList)
		 // 计算总数量
		    const totalCount = this.cartList.reduce((sum, item) => sum + item.quantity, 0)
		    uni.$emit('cartUpdated', totalCount)
      }
    },
    increaseQuantity(index) {
      this.cartList[index].quantity++
	  uni.setStorageSync('cartList2', this.cartList)
	   // 计算总数量
	      const totalCount = this.cartList.reduce((sum, item) => sum + item.quantity, 0)
	      uni.$emit('cartUpdated', totalCount)
    },
	//提交订单
	confirmGoods() {
	      uni.showModal({
	        title: '确认',
	        content: '您已确认好商品？',
	        success: (res) => {
	          if (res.confirm) {
	            this.showAddressModal = true;  // 显示收获信息弹窗
	          }
	        }
	      });
	    },
		//规则判断
		 confirmSubmit() {
		      // 简单验证收货信息是否填写
		      if (!this.receiverAddress || !this.receiverPhone || !this.receiverName) {
		        uni.showToast({
		          title: '请完整填写收获信息',
		          icon: 'none'
		        });
		        return;
		      }
			   //验证手机号格式
			    const phoneRegex = /^1[3-9]\d{9}$/
			    if (!phoneRegex.test(this.receiverPhone)) {
			      uni.showToast({
			        title: '手机号格式错误',
			        icon: 'none'
			      })
			      return
			    }
		      uni.showModal({
		        title: '确认订单',
		        content: '请确认是否提交订单',
		        success: (res) => {
		          if (res.confirm) {
		            this.showAddressModal = false;
		            this.submitOrder();
		          }
		          // 否则保持弹窗打开，用户可以修改信息
		        }
		      });
		    },
    submitOrder() {
		if(JSON.stringify(this.cartList) === JSON.stringify(this.stored) && this.cartList.length > 0){
			uni.removeStorageSync('cartList')
			uni.$emit('clearCartList')
			console.log('cartList与stored相同，已清除cartList缓存')
		}
		if(JSON.stringify(this.cartList) === JSON.stringify(this.stored2) && this.cartList.length > 0){
			uni.removeStorageSync('cartList2')
			uni.$emit('clearCartList2')
			console.log('cartList与stored2相同，已清除cartList2缓存')
		}
		const userId = uni.getStorageSync("parentId") || uni.getStorageSync("userId")
		const role = uni.getStorageSync("role")
		console.log(userId,"--------177")
      const data = {
        cartList: this.cartList.map(item => ({
          goodId: item.id,//商品ID
          goodName: item.name,//商品名字
          specText: item.specText,//商品描述
          quantity: item.quantity || 1,//商品数量
		  goodOriginalPrice:item.oldPrice,//商品原价
          goodDiscountPrice: item.price,//商品折后价
        })),
        totalAmount: this.totalMoney,//总价
        campusId: this.cartList[0].campusId,//校区Id
        storeId: userId,//用户Id
		role,//角色类型
        // userId: this.cartList[0].userId,//用户角色
		receiverName:this.receiverName,//收件人
		receiverPhone:this.receiverPhone,//收件人手机号
		receiverAddress:this.receiverAddress,//收件人地址
		distributionId:this.distributionId,//分销员Id
      }
	  console.log(data,"---------提交的订单信息")
	  //插入订单
      submitOrders(data).then(res => {
        uni.removeStorageSync('cartList')
        this.cartList = []
		uni.showToast({
		  icon: 'none',
		  title: res.message,
		  duration: 2000
		});
		// wx.showLoading({
		//   title: res.message,
		//   mask: true
		// });

        // totalMoney是计算属性，不能直接赋值，这里不用管
        console.log(res.message, "---------109")
		uni.navigateTo({
          url: '/pages/order-center/order-center'
        })
        // uni.showModal({
        //   title: '确认支付',
        //   content: '是否使用余额支付？',
        //   confirmText: '余额支付',
        //   cancelText: '取消',
        //   success: (modalRes) => {
        //     if (modalRes.confirm) {
        //       this.usePay(res.tradNo)
        //     } else if (modalRes.cancel) {
        //       uni.switchTab({
        //         url: '/pages/userCenter/userCenter'
        //       })
        //     }
        //   }
        // })
      }).catch(() => {
        uni.showToast({
          icon: 'none',
          title: '操作失败，请检查网络',
          duration: 2000
        })
      })
    },
    usePay(orderNo) {
      if (!orderNo) {
        uni.showToast({ title: '订单错误', duration: 2000 })
        return
      }
      payOrder(orderNo).then(res => {
        uni.showToast({
          title: res.message || '支付成功',
          icon: 'success',
          duration: 3000
        })
        uni.switchTab({
          url: '/pages/userCenter/userCenter'
        })
      }).catch(err => {
        uni.showToast({
          title: err.message || '支付失败',
          icon: 'none',
          duration: 3000
        })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/userCenter/userCenter'
          })
        }, 1500)
      })
    }
  }
}
</script>

<style>
.order-page {
  background-color: #f8f8f8;
  min-height: 100vh;
}
.modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex; justify-content: center; align-items: center;
  z-index: 1000;
}
.modal-container {
  width: 90%;
  background: white;
  border-radius: 10px;
  padding: 20px;
}
.modal-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
}
.modal-body .input {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 8px;
  border-radius: 5px;
}
.modal-footer {
  display: flex;
  justify-content: space-between;
}
</style>
